package com.example.thymelplay.config;

import com.example.thymelplay.service.MyUserService;
import com.example.thymelplay.service.impl.MyUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return  new BCryptPasswordEncoder();
    }
    @Autowired
    private MyUserServiceImpl myUserService;
// 账号和密码的来源
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserService).passwordEncoder(passwordEncoder());
    }
// 设置认证规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 放行/login路径 请求成功将会跳转到 /main
        http.formLogin()
                .loginProcessingUrl("/login")
                // 自定义登录页面 也就是放行该页面
                .loginPage("/login.html")
                .successForwardUrl("/main").permitAll();
        // 当没有权限是 进入 403页面
        http.exceptionHandling().accessDeniedPage("/403.html");
        // 解决密令问题
        http.csrf().disable();

        //
        http.authorizeRequests()
                .anyRequest().authenticated();
    }

}
